package com.gen.velocity.service.impl;

import com.gen.velocity.mapper.SysGeneratorMapper;
import com.gen.velocity.service.SysGeneratorService;
import com.gen.velocity.utils.GenUtils;
import com.gen.velocity.vo.TableSearchVO;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

/**
 * @author lijingyang
 * @Title:
 * @Package
 * @Description:
 * @date 2021/7/28 19:13
 */
@Service
public class SysGeneratorServiceImpl implements SysGeneratorService {
    @Autowired
    private SysGeneratorMapper sysGeneratorMapper;

    @Override
    public Map<String, Object> queryList(TableSearchVO map) {
        long count= sysGeneratorMapper .queryListCount(map);
        map.setTotal(count);
        List<Map<String,Object>> maps = sysGeneratorMapper.queryList(map);

        Map<String, Object> res=new HashMap<>();

        res.put("total",count);
        res.put("rows",maps);
        return res;
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        return sysGeneratorMapper.queryTotal(map);
    }

    @Override
    public Map<String, String> queryTable(String tableName) {
        return sysGeneratorMapper.queryTable(tableName);
    }

    @Override
    public List<Map<String, String>> queryColumns(String tableName) {
        return sysGeneratorMapper.queryColumns(tableName);
    }

    @Override
    public byte[] generatorCode(List<String> tableNames) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);

        for(String tableName : tableNames){
            //查询表信息
            Map<String, String> table = queryTable(tableName);
            //查询列信息
            List<Map<String, String>> columns = queryColumns(tableName);
            //生成代码
            GenUtils.generatorCode(table, columns, zip);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }
}
